// pages/category/category.js
import {Category}  from '../category/category-model.js';
var category = new Category();
Page({

  /**
   * 页面的初始数据
   */
  data: {
      chooseCategory:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      this.loadData();
  },


  loadData:function(){
    var that = this;
    //获取分类
    category.getCategory((categoryData)=>{
      console.log('categoryData:', categoryData);
      that.setData({
           categoryTypeArr: categoryData
      })
      //获取默认的分类商品
      var id = categoryData[0].id
      category.getProductByCategory(id, (res) => {
          var objData = {
            topImgUrl: categoryData[0].img.url,
            title: categoryData[0].name,
            products:res
          }
          //默认展示的内容
          that.setData({
             categoryProducts:objData
          })
      })
    })
  },

  //点击切换分类
  onCategoryProduct:function(e){
     var that = this;
     var id = that.getEvenData(e, 'id');
     
     //点击选中
     var index = that.getEvenData(e,'index');
     that.setData({
        chooseCategory:index
     })
     
     //获取点击分类
     var categoryArr = that.data.categoryTypeArr[index]
     var id = categoryArr.id;
     category.getProductByCategory(id, (res) => {
        var objData = {
          title: categoryArr.name,
          topImgUrl: categoryArr.img.url,
          products: res
        }
        //选择哪个分类就展示哪个数据
        that.setData({
            categoryProducts: objData
        })
     })
     //获取分类下的商品
    //  category.getOneCategory(id,(res)=>{
    //     var objData = {
    //       title:res.name,
    //       topImgUrl:res.img.url,
    //       products:res.products
    //     }
    //     that.setData({
    //       categoryProducts: objData
    //     })

    //  })

  },


  //点击商品获取商品详情
  onProductsItemTap:function(e){
     var that = this;
     var id = that.getEvenData(e,'id');
     wx.navigateTo({
       url: '../product/index?id='+id,
     })
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  /*获取Even里的参数 */
  getEvenData: function (e, key) {
    return e.currentTarget.dataset[key];
  }
})